package com.indusfo.spc.service.impl;

import com.indusfo.spc.common.pojo.Temporary;
import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.RepairDetailMapper;
import com.indusfo.spc.mapper.RepairMapper;
import com.indusfo.spc.pojo.Pro;
import com.indusfo.spc.pojo.Repair;
import com.indusfo.spc.pojo.RepairDetail;
import com.indusfo.spc.service.RepairService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.List;

@Service
public class RepairServiceImpl implements RepairService {

    private static final Logger logger = LoggerFactory.getLogger(RepairServiceImpl.class);

    @Resource
    private RepairMapper repairMapper;

    @Resource
    private RepairDetailMapper repairDetailMapper;


    /**
     * 下线信息更新
     *
     * @param repair
     * @return JSONObject
     */
    @Transient
    @Override
    public JSONObject updateRepair(Repair repair) {
        String remark = repair.getRemark();
        if (remark == null) {
            remark = "";
        }
        try {
            if (repair.getRepairId() == null) {
                throw new ParamsErrorException("请选择要更新的下线信息");
            }
            checkParam(repair, remark);
            List<Temporary> judge = judgeOperation(repair);
            // 调用存储过程
            int row = repairMapper.updateRepair(repair);
            if (row == 0) {
                throw new ModifyFailedException("数据编辑失败");
            } else {
                for (Temporary temporary : judge) {
                    Integer id = temporary.getId();
                    Integer pid = temporary.getPid();
                    String condition = temporary.getCondition();
                    RepairDetail repairDetail = new RepairDetail();
                    repairDetail.setRepairId(repair.getRepairId());
                    repairDetail.setProId(pid);
                    switch (condition) {
                        case "add":
                            repairDetail.setDataState(1);
                            repairDetailMapper.insertRepairDetail(repairDetail);
                            break;
                        case "update":
                            repairDetail.setRepairDetailId(id);
                            repairDetailMapper.updateByPrimaryKeySelective(repairDetail);
                            break;
                        case "del":
                            Long[] RepairListIds = {id.longValue()};
                            repairDetailMapper.delteRepairDetail(RepairListIds, 2);
                            break;
                        default:
                            break;
                    }
                }
            }
            return JSONObject.oK("编辑成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * wangqi
     * <p>
     * 判断操作
     *
     * @param repair
     * @return
     */
    private List<Temporary> judgeOperation(Repair repair) {
        Integer RepairId = repair.getRepairId();
        // 前端传输数据
        List<Temporary> list = repair.getList();
        // 数据库数据
        List<Temporary> list1 = repairDetailMapper.selectByRepairId(RepairId);

        List<Temporary> judge = new ArrayList<>();
        List<Temporary> delList = new ArrayList<>();

        for (Temporary ceshi : list) {
            Integer id = ceshi.getId();
            if (id == null) {
                ceshi.setCondition("add");
                for (Temporary ceshi11 : list1) {
                    if (ceshi11.getPid().equals(ceshi.getPid())) {
                        ceshi.setCondition("no");
                        delList.add(ceshi11);
                        break;
                    }
                }
                judge.add(ceshi);
                continue;
            }
            Integer rid = ceshi.getPid();
            for (Temporary ceshi1 : list1) {
                Integer id1 = ceshi1.getId();
                if (id.equals(id1)) {
                    Integer rid1 = ceshi1.getPid();
                    if (rid.equals(rid1)) {
                        delList.add(ceshi1);
                        ceshi.setCondition("no");
                        judge.add(ceshi);
                    } else {
                        delList.add(ceshi1);
                        ceshi.setCondition("update");
                        judge.add(ceshi);
                    }
                }
            }
        }
        list1.removeAll(delList);
        for (Temporary ceshi1 : list1) {
            ceshi1.setCondition("del");
            judge.add(ceshi1);
        }
        return judge;
    }

    /**
     * 下线信息查询（分页）
     *
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject selectAll(Repair repair) {
        List<Repair> listRepair = null;
        try {
            Integer pagesize = repair.getPagesize();
            Integer pageindex = repair.getPageindex();
            if (pagesize != null && pageindex != null) {
                repair.setIncept(pagesize * (pageindex - 1));
            }
            listRepair = repairMapper.selectAll(repair);
            if (listRepair.isEmpty()) {
                return JSONObject.oK("查询不到相关数据", listRepair, 0);
            }
            //查询分页总记录数
            int count = repairMapper.countRepair(repair); //返回查询到的总记录数
            return JSONObject.oK("查询成功", listRepair, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /***
     * 下线信息新增
     *
     * @param repair
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    @Transient
    public JSONObject insertRepair(Repair repair) {
        repair.setDataState(1);
        String remark = repair.getRemark();
        if (remark == null) {
            remark = "";
        }
        try {
            if (repair.getRepairId() != null) {
                throw new ParamsErrorException("新增时，不能填写id");
            }

            checkParam(repair, remark);

            int row = repairMapper.insertRepair(repair);
            Integer RepairId = repair.getRepairId();
            Long[] proIds = repair.getProIds();
            if (proIds.length != 0) {
                //批量新增  维修下线明细
                int rows = repairDetailMapper.insertRepairDetailAll(proIds, RepairId);
            }
            if (row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 1 启用  2 删除  3停用 下线信息
     *
     * @param repairIds
     * @param dataState
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Transient
    @Override
    public JSONObject deleteRepair(Long[] repairIds, Integer dataState) {
        try {
            if (dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            } else if (dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (repairIds == null) {
                throw new ParamsErrorException("下线工序ID不能为空");
            }
            // 执行存储过程
            int row = repairMapper.delteRepair(repairIds, dataState);
            if(dataState == 2){
                int i = repairDetailMapper.delteRepairDetailByRepairId(repairIds, dataState);
            }
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";
                        break;
                    case 2:
                        msg = "删除成功";
                        break;
                    case 3:
                        msg = "停用成功";
                        break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 参数校验
     *
     * @param repair
     * @param vcRemark
     */
    private void checkParam(Repair repair, String vcRemark) {
        if (repair.getRepairTypeId() != 1 && repair.getRepairTypeId() != 2) {
            throw new ParamsErrorException("工序类型错误");
        }
        if (StringUtils.isEmpty(repair.getRepairName())) {
            throw new ParamsErrorException("请填写下线工序名称");

        }
        if (repair.getRepairName().getBytes().length > 50) {
            throw new ParamsErrorException("下线工序名称名超过规定长度");
        }
        if (vcRemark.getBytes().length > 100) {
            throw new ParamsErrorException("说明字数超过规定长度");
        }
        // 名称不能重复
        Integer depCounts = repairMapper.selectRepair(repair);
        if (depCounts != 0) {
            throw new ParamsErrorException("该下线工序已存在");
        }
    }

    /**
     * 去添加查询（产品，任务单，批次）
     */
    @Override
    public JSONObject queryListRepairToInsert(Repair repair) {
        try {
            //获取页面的数据个数
            Integer pagesize = repair.getPagesize();
            //获取查询的页数
            Integer pageindex = repair.getPageindex();
            if (pagesize != null && pageindex != null) {
                repair.setIncept(pagesize * (pageindex - 1));
            }
            //执行查询操作
            List<Repair> repairList = repairMapper.queryListRepairToInsert(repair);

            //如果页数和页面数量都不为空的情况下进行计数
            if (repairList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, repairList, 0);
            } else {
                Integer count = repairMapper.countRepairToInsert(repair);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, repairList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }
}
